package org.whuims.web.standard;

import org.apache.shiro.SecurityUtils;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;
import org.whuims.entity.QuotaContext;
import org.whuims.entity.Standard;
import org.whuims.entity.vo.StandardVo;
import org.whuims.service.account.ShiroDbRealm;
import org.whuims.service.standard.StandardService;
import org.whuims.service.standard.StandardSolrService;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Qikai on 2016/11/7.
 */
@Controller
@RequestMapping(value = "/std")
public class StandardController {

    private static final String PAGE_SIZE = "10";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private StandardService stdService;
    @Autowired
    private StandardSolrService standardSolrService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                       @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
                       ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<Standard> stds = stdService.getStandardList(searchParams, pageNumber, pageSize, null);
        model.addAttribute("stds", stds);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "std/stdlist";
    }

    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
//        List<Standard> refStds=stdService.getRefStandards(std);
        model.addAttribute("std", std);
        URL apath = StandardController.class.getClassLoader().getResource("/");
        File dir = new File(apath.getPath()).getParentFile().getParentFile();
        String path = dir.getAbsolutePath() + "/resource/docs/" + std.getCatStd() + "/" + std.getPdfPath();
        File file = new File(path);
        System.out.println(file.getAbsolutePath());
        String exists = null;
        if (file.exists()) {
            exists = "true";
        }
        System.out.println(exists);
        model.addAttribute("exists", exists);
//        model.addAttribute("refStds", refStds);
        return "std/stddetail";
    }

    @RequestMapping(value = "ref/{id}", method = RequestMethod.GET)
    public String refStds(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
        List<Standard> refStds = stdService.getRefStandards(std);
        model.addAttribute("std", std);
        model.addAttribute("refStds", refStds);
        return "std/stdref";
    }

    @RequestMapping(value = "elements/{id}", method = RequestMethod.GET)
    public String elements(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
        model.addAttribute("std", std);
        return "std/elements";
    }

    @RequestMapping(value = "terms/{id}", method = RequestMethod.GET)
    public String terms(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
        model.addAttribute("std", std);
        return "std/stdterms";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("std", new Standard());
        model.addAttribute("action", "create");
        return "std/stdedit";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
        model.addAttribute("std", std);
        return "std/stdedit";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("standard") Standard standard, RedirectAttributes redirectAttributes) {
        System.out.println("修改成功");
        System.out.println(standard.getId());
        System.out.println(standard.getTitleCn());
        this.stdService.save(standard);
        redirectAttributes.addFlashAttribute("message", "编辑标准信息成功");
        return "redirect:/admin/std/list";
    }

    @RequestMapping(value = "quotas/{id}", method = RequestMethod.GET)
    public String quotas(@PathVariable("id") Long id, Model model) {
        Standard std = stdService.getStandard(id);
        Set<String> quotaStrList = stdService.detectQuotaStrs(std);
        List<QuotaContext> quotaContextList = stdService.detectQuotaContexts(std, quotaStrList);
        model.addAttribute("std", std);
        model.addAttribute("quotaStrList", quotaStrList);
        model.addAttribute("quotaContextList", quotaContextList);
        return "std/quotas";
    }

    @RequestMapping(value = "search", method = RequestMethod.GET)
    public String search(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                         @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
                         ServletRequest request) {
        String keyword = request.getParameter("keyword");
        keyword = keyword == null ? "*" : keyword;
        Page<Standard> stds = standardSolrService.findByTemplate(new PageRequest(pageNumber - 1, pageSize), keyword);
        model.addAttribute("stds", stds);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("keyword", keyword);
        model.addAttribute("total", stds.getTotalElements());
        return "std/search_result_simple";
    }

    @RequestMapping(value = "advancedSearch", method = RequestMethod.GET)
    public String advancedSearch(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                                 @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model, ServletRequest request) {
        StandardVo standardVo = new StandardVo();
        standardVo.setName(request.getParameter("name"));
        standardVo.setTitleEn(request.getParameter("titleEn"));
        standardVo.setTitleCn(request.getParameter("titleCn"));
        if (!Strings.isNullOrEmpty(request.getParameter("valid"))) {
            standardVo.setValid(Integer.parseInt(request.getParameter("valid")));
        }
        try {
            if (!Strings.isNullOrEmpty(request.getParameter("beginPublishDate")))
                standardVo.setBeginPublishDate(simpleDateFormat.parse(request.getParameter("beginPublishDate")));
            if (!Strings.isNullOrEmpty(request.getParameter("endPublishDate")))
                standardVo.setEndPublishDate(simpleDateFormat.parse(request.getParameter("endPublishDate")));
            if (!Strings.isNullOrEmpty(request.getParameter("beginEffectiveDate")))
                standardVo.setBeginEffectiveDate(simpleDateFormat.parse(request.getParameter("beginEffectiveDate")));
            if (!Strings.isNullOrEmpty(request.getParameter("endEffectiveDate")))
                standardVo.setEndEffectiveDate(simpleDateFormat.parse(request.getParameter("endEffectiveDate")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!Strings.isNullOrEmpty(request.getParameter("quotas"))) {
            standardVo.setQuotas(request.getParameter("quotas"));
        }
        Page<Standard> stds = standardSolrService.findByTemplate(new PageRequest(pageNumber - 1, pageSize), standardVo);
        model.addAttribute("stds", stds);
        model.addAttribute("sortType", "auto");
        StringBuilder stringBuilder = new StringBuilder();
        if (!Strings.isNullOrEmpty(standardVo.getTitleCn())) {
            stringBuilder.append("titleCn=" + standardVo.getTitleCn());
        }
        if (!Strings.isNullOrEmpty(standardVo.getTitleEn())) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                stringBuilder.append("&titleEn=" + standardVo.getTitleEn());
            else stringBuilder.append("titleEn=" + standardVo.getTitleEn());
        }
        if (!Strings.isNullOrEmpty(standardVo.getName())) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                stringBuilder.append("&name=" + standardVo.getName());
            else stringBuilder.append("name=" + standardVo.getName());
        }
        if (standardVo.getBeginPublishDate() != null) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString())) {
                if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                    stringBuilder.append("&beginPublishDate=" + standardVo.getBeginPublishDate().toLocaleString());
                else stringBuilder.append("beginPublishDate=" + standardVo.getBeginPublishDate().toLocaleString());
            }
        }
        if (standardVo.getEndPublishDate() != null) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                stringBuilder.append("&endPublishDate=" + standardVo.getEndPublishDate().toLocaleString());
            else stringBuilder.append("endPublishDate=" + standardVo.getEndPublishDate().toLocaleString());
        }
        if (standardVo.getBeginEffectiveDate() != null) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                stringBuilder.append("&beginEffectiveDate=" + standardVo.getBeginEffectiveDate().toLocaleString());
            else stringBuilder.append("beginEffectiveDate=" + standardVo.getBeginEffectiveDate().toLocaleString());
        }
        if (standardVo.getEndEffectiveDate() != null) {
            if (!Strings.isNullOrEmpty(stringBuilder.toString()))
                stringBuilder.append("&endEffectiveDate=" + standardVo.getEndEffectiveDate().toLocaleString());
            else stringBuilder.append("endEffectiveDate=" + standardVo.getEndEffectiveDate().toLocaleString());
        }
        model.addAttribute("searchParams", stringBuilder.toString());
        model.addAttribute("total", stds.getTotalElements());

        return "std/search_result_adv";
    }

    @RequestMapping(value = "seniorSearch", method = RequestMethod.GET)
    public String seniorSearch() {
        return "std/advanced_search";
    }

    @ModelAttribute
    public void getStandard(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
        if (id != -1) {
            model.addAttribute("standard", stdService.getStandard(id));
        }
    }

    @RequestMapping(value = "searchentry", method = RequestMethod.GET)
    public String simpleSearch() {
        return "std/search";
    }

    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

}
